package com.graduation.sports.ui.fragment;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.graduation.sports.R;
import com.graduation.sports.adapter.DailyTrainAdapter;
import com.graduation.sports.adapter.SpaceItemDecoration;
import com.graduation.sports.adapter.SportCalendarAdapter;
import com.graduation.sports.base.BaseFragment;
import com.graduation.sports.bean.DailyExerciseInfo;
import com.graduation.sports.bean.EveryDaySteps;
import com.graduation.sports.bean.PathRecord;
import com.graduation.sports.bean.SportDiaryBean;
import com.graduation.sports.bean.SportMotionRecord;
import com.graduation.sports.db.DataManager;
import com.graduation.sports.db.RealmHelper;
import com.graduation.sports.ui.widget.CustomWeekBar;
import com.graduation.sports.util.DateUtils;
import com.graduation.sports.util.MySp;
import com.graduation.sports.util.UIHelper;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ProjectName: sports
 * @Package: com.graduation.sports.ui.fragment
 * @ClassName: TrainingFragment
 * @Description: java类作用描述
 * @Author: APC
 * @CreateDate: 2021/2/22 10:57
 * @Version: 1.0
 */
public class TrainingFragment extends BaseFragment {

    @BindView(R.id.tv_month_day)
    TextView mTextMonthDay;
    @BindView(R.id.tv_year)
    TextView mTextYear;
    @BindView(R.id.tv_lunar)
    TextView mTextLunar;
    @BindView(R.id.tv_current_day)
    TextView mTextCurrentDay;
    @BindView(R.id.calendarView)
    CalendarView mCalendarView;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.calendarLayout)
    CalendarLayout mCalendarLayout;
    @BindView(R.id.sport_achievement)
    LinearLayout sport_achievement;
//    @BindView(R.id.up_btn_check)
//    ImageView btnCheck;
    @BindView(R.id.tv_step)
    TextView tvStep;

    private int mYear;
    private DailyTrainAdapter myAdapter;
    private List<PathRecord> sportList = new ArrayList<>(0);
    private List<DailyExerciseInfo> exerciseInfos = new ArrayList<>(0);
    private List<SportDiaryBean> diaryBeans = new ArrayList<>();

    private DataManager dataManager = null;



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_training;
    }

    @Override
    protected void initEventAndData() {
        dataManager = new DataManager(new RealmHelper());
        mYear = mCalendarView.getCurYear();
        mTextYear.setText(String.valueOf(mYear));
        mTextMonthDay.setText(UIHelper.getString(R.string.date_month_day, mCalendarView.getCurMonth(), mCalendarView.getCurDay()));
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(getResources().getDimensionPixelSize(R.dimen.line)));
//        adapter = new SportCalendarAdapter(R.layout.adapter_sportcalendar, sportList);
        myAdapter = new DailyTrainAdapter(getContext(), exerciseInfos);
        mRecyclerView.setAdapter(myAdapter);

        mCalendarView.setWeekStarWithSun();

        mCalendarView.setWeekBar(CustomWeekBar.class);
        upDateUI();
        initListener();
        
        getStep();

    }

    private void getStep() {
        if (LitePal.isExist(EveryDaySteps.class, "today = ?", DateUtils.getOldDate(0))) {
            tvStep.setText(LitePal.where("today = ?", DateUtils.getOldDate(0)).find(EveryDaySteps.class).get(0).getTodaysteps() + "");
        } else {
            tvStep.setText("0");
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            upDateUI();
            getStep();
        }
    }

    private void upDateUI() {
        loadSportData();

        getSports(DateUtils.formatStringDateShort(mCalendarView.getCurYear(), mCalendarView.getCurMonth(), mCalendarView.getCurDay()));
    }

    @OnClick({R.id.fl_current, R.id.tv_month_day})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fl_current:
                mCalendarView.scrollToCurrent();
                break;
            case R.id.tv_month_day:
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mCalendarView.showYearSelectLayout(mYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mYear));
                break;
//            case R.id.up_btn_check:
//                Intent intent = new Intent();
//                intent.putExtra("sportType", "跑步");
//                intent.setClass(getActivity(), SportsActivity.class);
//                startActivity(intent);
//                break;
//            case R.id.reBack:
//                showTipDialog("退出登录",
//                        "退出登录后将会删除历史数据,\n下次登录依然可以使用本账号!",
//                        () -> logOut());
//                break;
            default:
                break;
        }
    }

    private void loadSportData() {
        try {
            List<SportMotionRecord> records = dataManager.queryRecordList(Integer.parseInt(SPUtils.getInstance().getString(MySp.USERID, "0")));
            if (null != records) {
                Map<String, Calendar> map = new HashMap<>();
                for (SportMotionRecord record : records) {
                    String dateTag = record.getDateTag();
                    String[] strings = dateTag.split("-");
                    int year = Integer.parseInt(strings[0]);
                    int month = Integer.parseInt(strings[1]);
                    int day = Integer.parseInt(strings[2]);
                    map.put(getSchemeCalendar(year, month, day, 0xFFCC0000, "记").toString(),
                            getSchemeCalendar(year, month, day, 0xFFCC0000, "记"));
                }
                //此方法在巨大的数据量上不影响遍历性能，推荐使用
                mCalendarView.setSchemeDate(map);
            }
        } catch (Exception e) {
            LogUtils.e("获取运动数据失败", e);
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        calendar.addScheme(new Calendar.Scheme());
        return calendar;
    }

    private void getSports(String dateTag) {
        exerciseInfos = LitePal.where("timestamp = ?",dateTag).find(DailyExerciseInfo.class);
        diaryBeans = LitePal.where("date = ?",dateTag).find(SportDiaryBean.class);
        if (exerciseInfos.size() <=0 && diaryBeans.size() <=0) {
            sport_achievement.setVisibility(View.GONE);
        } else {
            if (exerciseInfos.size() > 0) {
                myAdapter.update(exerciseInfos);
            }
            if (diaryBeans.size() > 0 ) {

            }
        }
    }

    private void initListener() {
        mCalendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                mTextLunar.setVisibility(View.VISIBLE);
                mTextYear.setVisibility(View.VISIBLE);
                mTextMonthDay.setText(UIHelper.getString(R.string.date_month_day, calendar.getMonth(), calendar.getDay()));
                mTextYear.setText(String.valueOf(calendar.getYear()));
                mTextLunar.setText(calendar.getLunar());
                mYear = calendar.getYear();

                getSports(DateUtils.formatStringDateShort(calendar.getYear(), calendar.getMonth(), calendar.getDay()));

                LogUtils.d("onDateSelected", "  -- " + calendar.getYear() +
                        "  --  " + calendar.getMonth() +
                        "  -- " + calendar.getDay() +
                        "  --  " + isClick + "  --   " + calendar.getScheme());
            }
        });
        mCalendarView.setOnYearChangeListener(year -> {
            mTextMonthDay.setText(String.valueOf(year));
        });
    }
}
